<script setup lang="ts">
import { ref, reactive, watch, onMounted, onUnmounted, nextTick } from "vue";
import ReTable from "@/components/ReTable/index.vue";
import ReNewDialog from "@/components/ReNewDialog/index.vue";
import ReImageDialog from "@/components/ReImageDialog/index.vue";
import { useSettingStoreHook } from "@/store/modules/settings";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import type { Action } from "element-plus";
defineOptions({
  name: "blindBoxList"
});
interface ValueType {
  val: {
    buttonType: string;
  };
  row: object;
}
interface FormType {
  title: string;
  group: string;
  buyType: string;
  top_image: string;
  bottom_image: string;
  tag: string;
  price: string;
  lucky_price: string;
  star_stone_deduction_ratio: string;
  is_new_user: string;
  sort: string;
  status: string;
}
const dialogCreateVisible = ref(false);
const dialogImageSelectVisible = ref(false);

const pureSetting = useSettingStoreHook();
const showViewer = ref(false);
const imageUrl = ref("");
const dialogTitle = ref("");
const deleteModal = () => {
  ElMessageBox.confirm("确定要删除选中的盲盒分类吗?", "提示", {
    distinguishCancelAndClose: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
    })
    .catch((action: Action) => {
      ElMessage({ type: "info", message: "取消删除" });
    });
};
watch(
  () => pureSetting.buttonInfo,
  (newValue, oldValue) => {
    if (Object.keys(newValue).length !== 0) {
      let value = newValue as ValueType;
      console.log(value);
      switch (value.val.buttonType) {
        case "delete":
          deleteModal();
          break;
        case "edit":
          dialogTitle.value = "修改盲盒分类信息";
          dialogCreateVisible.value = true;
          break;
      }
    }
  },
  {
    immediate: true,
    deep: true
  }
);
watch(
  () => pureSetting.url,
  (newValue, oldValue) => {
    if (newValue) {
      imageUrl.value = newValue;
      showViewer.value = true;
    }
  },
  {
    immediate: true,
    deep: true
  }
);
// 关闭查看器
const closeViewer = () => {
  showViewer.value = false;
  pureSetting.setUrl("");
};
const blindBoxForm = reactive<FormType>({
  title: "",
  group: "",
  buyType: "",
  top_image: "",
  bottom_image: "",
  tag: "",
  price: "",
  lucky_price: "",
  star_stone_deduction_ratio: "",
  is_new_user: "1",
  sort: "",
  status: "1"
} as FormType);
const rules = reactive<FormRules>({
  title: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  group: [{ required: true, message: "请输入所属概率分组", trigger: "blur" }],
  buyType: [{ required: true, message: "请选择购买方式", trigger: "blur" }],
  top_image: [{ required: true, message: "请上传顶部图片", trigger: "blur" }],
  bottom_image: [
    { required: true, message: "请上传底部图片", trigger: "blur" }
  ],
  tag: [{ required: true, message: "请输入标签", trigger: "blur" }],
  price: [{ required: true, message: "请输入单次购买价格", trigger: "blur" }],
  lucky_price: [{ required: true, message: "请输入抽奖价格", trigger: "blur" }],
  star_stone_deduction_ratio: [
    { required: true, message: "请输入星石抵扣比例", trigger: "blur" }
  ],
  is_new_user: [
    { required: true, message: "请选择是否新用户专享", trigger: "blur" }
  ],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
  status: [{ required: true, message: "请选择是否启用", trigger: "blur" }]
} as FormRules);
const ruleFormRef = ref<FormInstance>();
const buyTypeOptions = ref([
  {
    label: "五谷丰登",
    value: "5",
    switch: false
  },
  {
    label: "事事如意",
    value: "4",
    switch: false
  },
  {
    label: "三神俱喜",
    value: "3",
    switch: false
  },
  {
    label: "双喜临门",
    value: "2",
    switch: false
  },
  {
    label: "一发入魂",
    value: "1",
    switch: false
  }
]);
const handleCloseDialog = () => {
  console.log("关闭弹窗");
  resetForm(ruleFormRef.value);
  dialogTitle.value = "";
};
const handleConfirmDialog = () => {
  console.log("确认弹窗");
  submitForm(ruleFormRef.value);
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      resetForm(formEl);
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogCreateVisible.value = false;
};
const handleGetCreate = () => {
  dialogTitle.value = "添加盲盒分类";
  dialogCreateVisible.value = true;
};
const handleChangeBuyType = (val: boolean, index: number) => {
  console.log(val, index);
  buyTypeOptions.value[index].switch = val;
  console.log(buyTypeOptions);
};
const imageType = ref("");
const handleSelctImage = type => {
  imageType.value = type;
  dialogImageSelectVisible.value = true;
};
// 获取到顶部图
const handleGetTopImage = (arr: any) => {
  blindBoxForm[imageType.value] = arr[0].url;
  console.log(imageType.value);
  dialogImageSelectVisible.value = false;
  imageUrl.value = "";
};
const handleGetDeleteIds = (deleteIds: string[]) => {
  deleteModal();
};
</script>
<template>
  <div class="blind-box-list-container">
    <el-image-viewer
      v-if="showViewer"
      :url-list="[imageUrl]"
      @close="closeViewer"
    />
    <ReTable
      type="blindBoxList"
      class="content-body"
      create-btn-text="添加盲盒分类"
      delete-btn-text="删除选中盲盒分类"
      @delete="handleGetDeleteIds"
      @create="handleGetCreate"
    />
    <ReNewDialog
      :visible="dialogCreateVisible"
      :dialogTitle="dialogTitle"
      @close="handleCloseDialog"
      @confirm="handleConfirmDialog"
    >
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="blindBoxForm"
          :rules="rules"
          label-width="140px"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="blindBoxForm.title" />
          </el-form-item>
          <el-form-item label="所属概率分组" prop="group">
            <el-input v-model="blindBoxForm.group" />
          </el-form-item>
          <el-form-item label="所属概率分组" prop="buyType">
            <el-row>
              <el-col
                v-for="(item, index) in buyTypeOptions"
                :key="index"
                :span="4"
                class="mr-3"
              >
                <el-switch
                  v-model="item.switch"
                  :label="item.label"
                  inline-prompt
                  :active-text="item.label"
                  :inactive-text="item.label"
                  @change="handleChangeBuyType(item.switch, index)"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="顶部图片" prop="top_image">
            <div>
              <el-button type="primary">上传图片</el-button>
              <el-button @click="handleSelctImage('top_image')">
                选择图片
              </el-button>
              <ReImageDialog
                :visible="dialogImageSelectVisible"
                @confirm="handleGetTopImage"
              />
              <div v-if="blindBoxForm.top_image != ''" class="mt-3">
                <el-image
                  style="width: 100px; height: 100px; border-radius: 10px"
                  :src="blindBoxForm.top_image"
                  fit="fill"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="底部图片" prop="bottom_image">
            <div>
              <el-button type="primary">上传图片</el-button>
              <el-button @click="handleSelctImage('bottom_image')">
                选择图片
              </el-button>
              <ReImageDialog
                :visible="dialogImageSelectVisible"
                @confirm="handleGetTopImage"
              />
              <div v-if="blindBoxForm.bottom_image != ''" class="mt-3">
                <el-image
                  style="width: 100px; height: 100px; border-radius: 10px"
                  :src="blindBoxForm.bottom_image"
                  fit="fill"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="标签" prop="tag">
            <el-input v-model="blindBoxForm.tag" placeholder="请输入标签" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input
              v-model="blindBoxForm.price"
              placeholder="请输入价格"
              type="number"
            />
          </el-form-item>
          <el-form-item label="幸运币价格" prop="lucky_price">
            <el-input
              v-model="blindBoxForm.lucky_price"
              placeholder="请输入幸运币价格"
              type="number"
            />
          </el-form-item>
          <el-form-item label="星石抵扣比例" prop="star_stone_deduction_ratio">
            <div class="flex items-end justify-between">
              <el-input
                v-model="blindBoxForm.star_stone_deduction_ratio"
                class="flex-1"
                placeholder="请输入星石抵扣比例"
                type="number"
              />
              <span class="text-xs text-neutral-400 ml-3">
                填写10代表10星石抵扣1元的
              </span>
            </div>
          </el-form-item>
          <el-form-item label="是否新用户活动" prop="is_new_user">
            <div class="flex items-center justify-between">
              <el-radio-group v-model="blindBoxForm.is_new_user">
                <el-radio value="1">否</el-radio>
                <el-radio value="2">是</el-radio>
              </el-radio-group>
              <span class="text-xs text-neutral-400 ml-10">
                如果是，则新用户首件0.01元
              </span>
            </div>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input
              v-model="blindBoxForm.sort"
              placeholder="请输入排序"
              type="number"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="blindBoxForm.status">
              <el-radio value="1">关闭</el-radio>
              <el-radio value="2">开启</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </template>
    </ReNewDialog>
  </div>
</template>
